import io
import time

from selenium import webdriver
from PIL import Image
import pytesseract
import requests
from io import BytesIO
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from 验证码识别 import ocr_val
from get_tips import get_tip
from get_fails import get_fail
from get_val_code import get_val

# 初始化Selenium WebDriver
driver = webdriver.Chrome()
# 打开目标网页
driver.get("http://valser.org/reg/2024/")
# 显式等待，确保页面已加载完成
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, "input[placeholder='请输入手机号码']")))

def send_and_get_duanxin():
    # 填写手机号码
    driver.find_element(By.CSS_SELECTOR, "input[placeholder='请输入手机号码']").send_keys("18801321911")
    png = driver.get_screenshot_as_png()  # 获取屏幕截图的PNG格式图片数据
    image = Image.open(io.BytesIO(png))
    image.save('captcha.png')
    get_val("captcha.png") # 存为：val_code.png
    with open('val_code.png', 'rb') as image_file:
        image_bytes = image_file.read()
    resp = requests.post("http://127.0.0.1:9898/ocr/file", files={'image': image_bytes})
    text = resp.content.decode('utf-8')
    # 填写验证码（根据实际情况可能需要调整选择器）
    driver.find_element(By.CSS_SELECTOR, "input[placeholder='请输入图中验证码']").send_keys(text)
    # 点击获取短信验证码按钮（根据实际情况可能需要调整选择器）
    driver.find_element(By.CSS_SELECTOR, "button.getverify").click()

send_and_get_duanxin()
i = 0

while(i < 100):
    # 接下来看是哪种错误：
    time.sleep(3)
    tip = driver.get_screenshot_as_png()  # 获取屏幕截图的PNG格式图片数据
    tip = Image.open(io.BytesIO(tip))
    tip.save('tip_png.png')

    # 获取两个位置的提示，来判断到底是什么问题
    get_tip("tip_png.png")
    get_fail("tip_png.png")

    # 第一个可能性是验证码错误
    if ocr_val("tip.png") == "请输入图中验证码":
        driver.refresh()
        time.sleep(2)
        send_and_get_duanxin()
    elif ocr_val("fail.png") == "发送失败":
        time.sleep(3)
        driver.refresh()
        time.sleep(2)
        send_and_get_duanxin()
    else:
        time.sleep(10000000)
    i += 1



